package com.changdu.seatunnel.admin.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@MappedTypes(List.class)
public class ListIntegerTypeHandler extends BaseTypeHandler<List<Integer>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Integer> parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null) {
            ps.setString(i, null);
            return;
        }
        String value = parameter.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(","));
        log.debug("Converting List<Integer> to String: {}", value);
        ps.setString(i, value);
    }

    @Override
    public List<Integer> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        log.debug("Converting String to List<Integer> from column {}: {}", columnName, value);
        return convertToList(value);
    }

    @Override
    public List<Integer> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        log.debug("Converting String to List<Integer> from column index {}: {}", columnIndex, value);
        return convertToList(value);
    }

    @Override
    public List<Integer> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        log.debug("Converting String to List<Integer> from callable statement column {}: {}", columnIndex, value);
        return convertToList(value);
    }

    private List<Integer> convertToList(String value) {
        if (value == null || value.trim().isEmpty()) {
            log.debug("Empty value, returning empty list");
            return new ArrayList<>();
        }
        try {
            List<Integer> result = Arrays.stream(value.split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            log.debug("Converted to List<Integer>: {}", result);
            return result;
        } catch (NumberFormatException e) {
            log.error("Error converting string to List<Integer>: {}", value, e);
            return new ArrayList<>();
        }
    }
} 